package com.raycloud.erp.omll.provider.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.omall.open.sdk.response.AuthResponse;
import com.raycloud.erp.omll.data.entity.MulPlatformUser;
import com.raycloud.erp.omll.data.entity.OmallSyncInfo;
import com.raycloud.erp.omll.data.mapper.MulPlatformUserMapper;
import com.raycloud.erp.omll.data.service.MulPlatformUserService;
import com.raycloud.erp.omll.data.service.OmallSyncInfoService;
import com.raycloud.erp.omll.provider.config.PullOrderConfig;
import com.raycloud.erp.omll.provider.constant.Constants;
import com.raycloud.erp.omll.provider.constant.OmallAppInfo;
import com.raycloud.erp.omll.provider.service.AccessTokenService;
import com.raycloud.erp.omll.provider.utils.OmallHttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


/**
 * @author 枫伦
 * @DESCRIPTION
 * @create 2021/1/6 11:09 上午
 */
@Service
@Slf4j
public class AccessTokenServiceImpl implements AccessTokenService {
    @Autowired
    private OmallHttpUtils omallHttpUtils;
    @Autowired
    private MulPlatformUserMapper mulPlatformUserMapper;

    @Autowired
    private PullOrderConfig pullOrderConfig;

    @Autowired
    private OmallSyncInfoService omallSyncInfoService;

    @Autowired
    private MulPlatformUserService mulPlatformUserService;
    /***
     * @DESCRIPTION: 第一次注册用户, 需要获取token, 添加订单拉取任务, 如果是用户删除, 就需要把对应的订单拉取任务的数据给逻辑删除掉
     * @Modified By:
     */
    /***
     * @DESCRIPTION: 获取并绑定洋葱凭平台的店铺token
     * @author 枫伦
     * @params: []
     * @return: void
     * @Date: 2021/1/6 12:55 下午
     * @Modified By:
     * @param mulPlatformUser
     */
    @Override
    @Async
    public MulPlatformUser getAccessToken(MulPlatformUser mulPlatformUser) {
        if (Objects.isNull(mulPlatformUser.getCompanyId()) || Objects.isNull(mulPlatformUser.getUserId())) {
            return null;
        }
        if (StringUtils.isNotBlank(mulPlatformUser.getAuthFieldList())) {
            JSONObject jsonObject = JSONObject.parseObject(mulPlatformUser.getAuthFieldList());
            //如果入参对象中直接包含了appkey和appsecret
            if (jsonObject.containsKey(OmallAppInfo.STR_APP_KEY) && jsonObject.containsKey(OmallAppInfo.STR_APP_SECRET)) {
                omllAccessToken(mulPlatformUser);
            } else {
                //入参不包含的情况直接从数据库中查询
                MulPlatformUser mulPlatformUser1 = mulPlatformUserService.getUserByUserIdCompanyId(mulPlatformUser);
                if (!Objects.isNull(mulPlatformUser1)) {
                    omllAccessToken(mulPlatformUser1);
                }
            }
        }
        return mulPlatformUser;
    }


    /***
     * @DESCRIPTION: 更新店铺的token, token过期是假, 订阅过期时间并且添加第一条订单拉取任务
     * @author 枫伦
     * @params: [mulPlatformUser, jsonObject]
     * @return: void
     * @Date: 2021/1/8 3:01 下午 
     * @Modified By:  
     */
    private void omllAccessToken(MulPlatformUser mulPlatformUser) {
        MulPlatformUser userByUserIdCompanyId = mulPlatformUserService.getUserByUserIdCompanyId(mulPlatformUser);
        if (Objects.isNull(userByUserIdCompanyId)) {
            return;
        }
        Map<String, Object> authMap = omallHttpUtils.getAuthMap(userByUserIdCompanyId);
        //获取token
        AuthResponse omallResponse = (AuthResponse) omallHttpUtils.getWithParams(Constants.RequestUrl.GET_ACCESS_TOKEN, null, AuthResponse.class, authMap);
        log.info("洋葱平台获取token结果:{}", omallResponse.getBody());
        userByUserIdCompanyId.setToken(omallResponse.getAccessToken());
        LocalDateTime now = LocalDateTime.now();
        userByUserIdCompanyId.setTokenExpire(now.plusHours(5L));
        userByUserIdCompanyId.setTokenExpire(now.plusYears(1L));
        userByUserIdCompanyId.setCreated(now);
        //更新苦衷的token
        mulPlatformUserMapper.updateById(userByUserIdCompanyId);
        //第一次拉取店铺中的订单
        String firstPullTimes = pullOrderConfig.getFirstPullTimes();
        String firstPullUnit = pullOrderConfig.getFirstPullUnit();
        if (firstPullUnit.equals(Constants.TimeUnit.DAYS)) {
            //计算开始时间
            DateTime dateTime = DateUtil.offsetDay(new Date(), 0 - (Integer.valueOf(firstPullTimes)));
            OmallSyncInfo omallSyncInfo = new OmallSyncInfo();
            omallSyncInfo.setCompanyId(userByUserIdCompanyId.getCompanyId())
                    .setUserId(userByUserIdCompanyId.getUserId())
                    .setSource(userByUserIdCompanyId.getSource())
                    .setEnableStatus(true)
                    .setItemSyncStatus(false)//不开启商品同步
                    .setTradeSyncStatus(true)//开启订单同步
                    .setLastImportTradeTime(dateTime);
            omallSyncInfoService.save(omallSyncInfo);
        }
    }

    public static void main(String[] args) {
        OmallHttpUtils omallHttpUtils = new OmallHttpUtils();
        HashMap<String, Object> authMap = new HashMap<>();
        authMap.put("app-key","e7a2e2d3a3");
        authMap.put("sign","4678b733e21c4ec9c4ee1f53cdc805fa");
        authMap.put("timestamp",1620369200940L);
        AuthResponse omallResponse = (AuthResponse) omallHttpUtils.getWithParams("https://ark.xiaohongshu.com/ark/open_api/v0/packages/62022465100394973", null, AuthResponse.class, authMap);

    }
}

